import axios from 'axios';

// 创建 axios 实例
const instance = axios.create({
    baseURL: 'https://goods.zzgoodqc.cn',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json',
    },
});

// 请求拦截器
instance.interceptors.request.use(
    (config) => {
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
instance.interceptors.response.use(
    (response) => {
        if (response.status === 200) {
            return response.data;
        } else {
            return Promise.reject(response.data);
        }
    },
    (error) => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    console.error('未授权，请重新登录');
                    break;
                case 404:
                    console.error('请求的资源不存在');
                    break;
                case 500:
                    console.error('服务器内部错误');
                    break;
                default:
                    console.error('请求失败', error.response.data);
            }
        } else {
            console.error('网络错误，请检查网络连接');
        }
        return Promise.reject(error);
    }
);

// 封装 GET 请求
export const get = (url, params = {}) => {
    return instance({
        url,
        method: 'get',
        params
    })
};

// 封装 POST 请求
export const post = (url, data = {}) => {
    return instance({
        url,
        method: 'post',
        data
    })
};

// 封装 PUT 请求
export const put = (url, data = {}) => {
    return instance({
        url,
        method: 'put',
        data
    })
};

// 封装 DELETE 请求
export const del = (url, params = {}) => {
    return instance({
        url,
        method: 'get',
        params
    })
};

// 导出实例
export default instance;